#!/usr/bin/python
#-*- coding:utf8

import urllib
import urllib2
from pyquery import PyQuery
import urlparse
import itchat
import time
import os.path
import sys
reload(sys)
sys.setdefaultencoding('utf8')

NotNoticeKeywords = ['步步高','诺亚舟', '好记星', '卡西欧', '快易典', '名人']
UserNick = 'Wind'
ChatRoomName = ''
UserName = ''
tasks = [
    {
        'keyword': '台式机',
        'param': '&start=2000&end=5000&divisionId=440300'
    }, {
        'keyword': '显示器 32寸',
        'param': '&start=200&end=500&divisionId=440300'
    }, {
        'keyword': '文曲星',
        'param': ''
    }, {
        'keyword': '电子词典',
        'param': ''
    }, {
        'keyword': '电子辞典',
        'param': ''
    }
]


def get_url(keyword, param):
    url = 'https://s.2.taobao.com/list/list.htm?st_edtime=1&ist=0%s&q=%s' % (
        param, urllib.quote(keyword.decode('utf8').encode('gbk')))
    return url

def checkNotNotice(title):
    for k in NotNoticeKeywords:
        if k in title:
            return True
    return False


def check(id):
    ID_FILE_NAME = 'id_list.txt'
    if os.path.exists(ID_FILE_NAME) == False:
        id_list = ['1']
        open(ID_FILE_NAME, 'w').write(repr(id_list))
    id_list = open(ID_FILE_NAME).read()
    id_list = eval(id_list)

    if id in id_list:
        return False

    id_list.append(id)
    open(ID_FILE_NAME, 'w+').write(repr(id_list))
    return True


def process(url):
    doc = PyQuery(url)
    item_info_list = doc('ul li div.item-info')
    for item_info in item_info_list:
        item_info = doc('ul li div.item-info').eq(0)
        item_url = item_info('div.item-pic a').attr('href')
        r = urlparse.urlparse(item_url)
        item_id = urlparse.parse_qs(r.query)['id'][0]
        if check(item_id) == False:
            continue
        item_title = item_info('h4.item-title').text()
        if checkNotNotice(item_title):
            continue
        item_price = item_info('div.item-price span.price em').text()
        item_description = item_info('div.item-description').text()
        item_url = item_info('div.item-pic a').attr('href')
        # item_location = item_info('div.item-location').text()
        item_img = item_info('div.item-pic a img').attr('src')
        img = urllib2.urlopen('https:' + item_img).read()
        open('1.jpg', 'wb').write(img)
        msg = "%s \n%s \n%s \nhttps:%s" % (
            item_title, item_price, item_description, item_url)
        print msg+'\n'
        itchat.send(msg, toUserName=UserName)
        itchat.send('@img@1.jpg', toUserName=UserName)


def chat_login():
    global UserName

    itchat.auto_login()
    if UserNick:
        UserName = itchat.search_friends(nickName=UserNick)[0]['UserName']
    else:
        UserName = itchat.search_chatrooms(
            ChatRoomName.decode('utf-8'))[0]['UserName']

    print UserName


def main():
    chat_login()
    while 1:
        for task in tasks:
            # url = get_url(task['keyword'],task['param'])
            # print url
            # process(url)
            try:
                url = get_url(task['keyword'], task['param'])
                # print url
                process(url)
            except Exception, e:
                print e
                pass
        time.sleep(10)


if __name__ == '__main__':
    main()
